﻿using Newtonsoft.Json;
using QD.Tools;
using QD.UpDownLoad;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using QD.SQLHelper;

namespace QD.SyncServers
{
    public partial class SyncStep4 : BaseFrm
    {
        private DateTime StartProcessDate = DateTime.Now;//开始处理时间

        private static string connStr_Source = DbConfig.Instance.GetDbDataBaseConnStr();
        private DbHelperSQL db = new DbHelperSQL(connStr_Source);
        public SyncStep4()
        {
            InitializeComponent();
            this.gridTable.AutoGenerateColumns = false;
            CheckForIllegalCrossThreadCalls = false;//支持多线程

            DataTable dtTableList = db.Query(string.Format(@"select SysTable,(CASE SysTableName
WHEN '' THEN SysTable
WHEN NULL THEN SysTable
ELSE SysTableName
END) as SysTableName, TableType, (CASE TableType
WHEN '0' THEN '平台程序配置'
WHEN '1' THEN '平台报表配置'
END) as TableTypeName from Sys_ConfigTable
where tableType = 0 or tableType = 1 ")).Tables[0];
            this.gridTable.DataSource = dtTableList;

            this.cbxTableType.Items.Add(new ComboBoxItem(string.Concat(0), string.Concat("平台程序配置")));
            this.cbxTableType.Items.Add(new ComboBoxItem(string.Concat(1), string.Concat("平台报表配置")));

            //默认全选
            this.cbxTableType.SelectAll();

            ////加载同步日志保存的服务器类型
            //ComboBoxItem itemSyncLogServerSourceType = new ComboBoxItem("SourceServer", "来源服务器");            
            //this.cbxSyncLogServerSourceType.Items.Add(itemSyncLogServerSourceType);
            //itemSyncLogServerSourceType = new ComboBoxItem("TargetServer", "目标服务器");
            //this.cbxSyncLogServerSourceType.Items.Add(itemSyncLogServerSourceType);            
        }

        private void SyncStep4_Load(object sender, EventArgs e)
        {
            this.label1.Text = "请确认需要同步的表";

            DataGridViewCheckBoxHeaderCell checkBoxHeaderCell = new DataGridViewCheckBoxHeaderCell();
            checkBoxHeaderCell.OnCheckBoxClicked += checkBoxHeaderCell_OnCheckBoxClicked;
            DataGridViewCheckBoxColumn checkColumn = (DataGridViewCheckBoxColumn)this.gridTable.Columns["IsChecked"];
            checkColumn.HeaderCell = checkBoxHeaderCell;
            checkColumn.HeaderCell.Value = string.Empty;
        }

        void checkBoxHeaderCell_OnCheckBoxClicked(object sender, datagridviewCheckboxHeaderEventArgs e)
        {
            for (int i = 0; i < gridTable.Rows.Count; i++)
            {
                gridTable.Rows[i].Cells[0].Value = e.CheckedState.ToString();
            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form frm = Application.OpenForms["SyncStep3"];
            if (frm == null)
            {
                frm = new SyncStep3();
                frm.ShowDialog();
            }
            else
            {
                frm.Show();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            bool syncSuccess = false;
            //取需要同步的表
            List<string> syncDataTableNamesList = new List<string>();
            int rowsCount = this.gridTable.Rows.Count;
            for (int i = 0; i < rowsCount; i++)
            {
                bool isChecked = this.gridTable.Rows[i].GetCellValueToBool("IsChecked");
                if (isChecked)
                {
                    syncDataTableNamesList.Add(this.gridTable.Rows[i].GetCellValueToString("SysTable"));
                }
            }
            ConfigInstanceHelper.ConfigInstance.SyncDataTableNames = string.Join(",", syncDataTableNamesList);//需要同步的表
            ConfigInstanceHelper.ConfigInstance.DeleteExpiredColumn = cbxDeleteExpiredColumn.Checked;//删除失效的栏位
            ConfigInstanceHelper.ConfigInstance.EnabledSyncLog = true;// cbxEnabledSyncLog.Checked;//是否记录同步日志

            ConfigInstanceHelper.ConfigInstance.SyncLogServerSourceType = "SourceServer";
            ConfigInstanceHelper.ConfigInstance.SyncLogDBName = "QDDevPlat_V4";// txtSyncLogDBName.Text;//同步日志记录到哪个数据库，如果为空，记录到目标数据库
            ConfigInstanceHelper.ConfigInstance.OperateUserID = DbConfig.Instance.Uid;//操作用户ID
            //获取当前登录用户名称
            if (!string.IsNullOrEmpty(DbConfig.Instance.Uid))
            {
                string connStr = DbConfig.Instance.GetDbDataBaseConnStr();//取连接字符串
                DbHelperSQL dbHelperSQL = new DbHelperSQL(connStr);
                object userNameObject = dbHelperSQL.ExecuteScalar("SELECT UserName FROM Sys_UidPwd WHERE Uid = '" + DbConfig.Instance.Uid + "'");
                ConfigInstanceHelper.ConfigInstance.OperateUserName = string.Concat(userNameObject);
            }

            //取来源服务器配置
            string errorMessage = "";

            DataTable dtSyncConfig = db.Query(string.Format("SELECT top 1 * FROM Sys_SyncConfig")).Tables[0];
            if (dtSyncConfig != null && dtSyncConfig.Rows.Count > 0)
            {
                ConfigInstanceHelper.ConfigInstance.SourceServerName = string.Concat(dtSyncConfig.Rows[0]["ServerName"]);
                ConfigInstanceHelper.ConfigInstance.SourceServerNetName = string.Concat(dtSyncConfig.Rows[0]["ServerIP"]);
                ConfigInstanceHelper.ConfigInstance.SourceUserId = string.Concat(dtSyncConfig.Rows[0]["ServerUid"]);
                ConfigInstanceHelper.ConfigInstance.SourceUserPassword = string.Concat(dtSyncConfig.Rows[0]["ServerPwd"]);
                ConfigInstanceHelper.ConfigInstance.CreateSyncDBProcCommand = string.Concat(dtSyncConfig.Rows[0]["SyncCmd"]);
            }

            //确认升级
            string msgText = "请确认以下信息无误后完成升级："
                 + System.Environment.NewLine + "来源产品:" + ConfigInstanceHelper.ConfigInstance.SourceProductName
                 + System.Environment.NewLine + "目标产品:" + ConfigInstanceHelper.ConfigInstance.TargetProductName
                 + System.Environment.NewLine + "目标产品所在服务器名称(IP):" + ConfigInstanceHelper.ConfigInstance.TargetServerName
                 + System.Environment.NewLine + "启用事务一致性:" + (ConfigInstanceHelper.ConfigInstance.EnabledTran ? "是" : "否")
                 + System.Environment.NewLine + "删除失效的栏位:" + (ConfigInstanceHelper.ConfigInstance.DeleteExpiredColumn ? "是" : "否")
                 + System.Environment.NewLine + "配置库要同步数据的表:" + ConfigInstanceHelper.ConfigInstance.SyncDataTableNames
                 ;
            if (MessageBox.Show(msgText, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            this.cbxTableType.Enabled = false;
            this.gridTable.Enabled = false;
            this.cbxDeleteExpiredColumn.Enabled = false;
            this.btnPrev.Enabled = false;
            this.btnNext.Enabled = false;

            //创建进度计时器
            Timer processTimer = new Timer();
            processTimer.Enabled = true;
            processTimer.Interval = 1000;
            processTimer.Tick += new System.EventHandler(this.ProcessTimer_Tick);
            processTimer.Start();

            StartProcessDate = DateTime.Now;
            this.lblStatus.Visible = true;
            bool execResult = false;
            Task task = Task.Run(() =>
            {
                execResult = ExecSync(out errorMessage);//执行同步
            }).ContinueWith(t =>
            {
                processTimer.Stop();
                processTimer = null;
                this.lblStatus.Text = "同步结束";
                this.cbxTableType.Enabled = true;
                this.gridTable.Enabled = true;
                this.cbxDeleteExpiredColumn.Enabled = true;
                this.btnPrev.Enabled = true;
                this.btnNext.Enabled = true;

                //if (execResult)
                //{
                //    MessageBox.Show("同步成功.");
                //}
                //else
                //{
                //    MessageBox.Show("同步失败." + errorMessage);
                //}
                this.Hide();
                Form frm = Application.OpenForms["SyncStep5"];
                if (frm == null)
                {
                    frm = new SyncStep5();
                    frm.ShowDialog();
                }
                else
                {
                    frm.Show();
                }
            });
        }

        private bool ExecSync(out string errorMessage)
        {
            errorMessage = "";
            bool syncSuccess = false;
            string masterErrorMessage = "";//主数据库同步错误信息
            string configErrorMessage = "";//配置数据库同步错误信息

            //取需要同步的表
            List<string> syncDataTableNamesList = new List<string>();
            int rowsCount = this.gridTable.Rows.Count;
            for (int i = 0; i < rowsCount; i++)
            {
                if (gridTable.Rows[i].Cells[0].Value != null && !string.IsNullOrEmpty(gridTable.Rows[i].Cells[0].Value.ToString()) && bool.Parse(gridTable.Rows[i].Cells[0].Value.ToString()))
                {
                    syncDataTableNamesList.Add(this.gridTable.Rows[i].GetCellValueToString("SysTable"));
                }
            }
            ConfigInstanceHelper.ConfigInstance.SyncDataTableNames = string.Join(",", syncDataTableNamesList);

            //取来源服务器配置
            //string apiUrl = System.Configuration.ConfigurationManager.AppSettings.Get("SyncAPIBaseUrl") + "api/Platform/GetSyncConfig?uid={0}&pwd={1}";
            //bool downloadSuccess = false;
            //object dbObject = null;
            //apiUrl = string.Format(apiUrl, ConfigInstanceHelper.ConfigInstance.LoginUserId, ConfigInstanceHelper.ConfigInstance.LoginUserPassword);
            //try
            //{
            //    //登录有效性验证
            //    WebClientHelper.ClientResultDTO result = WebClientHelper.DownloadString(apiUrl);
            //    if (result != null)
            //    {
            //        downloadSuccess = result.success;
            //        errorMessage = result.error;
            //        dbObject = result.data;
            //    }
            //    else
            //    {
            //        errorMessage = "获取同步配置失败";
            //    }
            //}
            //catch (Exception ex)
            //{
            //    errorMessage = ex.Message;
            //    ConfigInstanceHelper.ConfigInstance.ErrorMessage = errorMessage;
            //    return false;
            //}
            //if (downloadSuccess && dbObject != null)
            //{
            //    DataTable dtSyncConfig = JsonConvert.DeserializeObject<DataTable>(dbObject.ToString());
            //    if (dtSyncConfig != null && dtSyncConfig.Rows.Count > 0)
            //    {
            //        ConfigInstanceHelper.ConfigInstance.SourceServerName = string.Concat(dtSyncConfig.Rows[0]["ServerName"]);
            //        ConfigInstanceHelper.ConfigInstance.SourceServerNetName = string.Concat(dtSyncConfig.Rows[0]["ServerIP"]);
            //        ConfigInstanceHelper.ConfigInstance.SourceUserId = string.Concat(dtSyncConfig.Rows[0]["ServerUid"]);
            //        ConfigInstanceHelper.ConfigInstance.SourceUserPassword = string.Concat(dtSyncConfig.Rows[0]["ServerPwd"]);
            //        ConfigInstanceHelper.ConfigInstance.CreateSyncDBProcCommand = string.Concat(dtSyncConfig.Rows[0]["SyncCmd"]);
            //    }
            //    else
            //    {
            //        ConfigInstanceHelper.ConfigInstance.ErrorMessage = errorMessage;
            //        return false;
            //    }
            //}
            //else
            //{
            //    ConfigInstanceHelper.ConfigInstance.ErrorMessage = errorMessage;
            //    return false;
            //}
            DataTable dtSyncConfig = db.Query(string.Format("SELECT top 1 * FROM Sys_SyncConfig")).Tables[0];
            if (dtSyncConfig != null && dtSyncConfig.Rows.Count > 0)
            {
                ConfigInstanceHelper.ConfigInstance.SourceServerName = string.Concat(dtSyncConfig.Rows[0]["ServerName"]);
                ConfigInstanceHelper.ConfigInstance.SourceServerNetName = string.Concat(dtSyncConfig.Rows[0]["ServerIP"]);
                ConfigInstanceHelper.ConfigInstance.SourceUserId = string.Concat(dtSyncConfig.Rows[0]["ServerUid"]);
                ConfigInstanceHelper.ConfigInstance.SourceUserPassword = string.Concat(dtSyncConfig.Rows[0]["ServerPwd"]);
                ConfigInstanceHelper.ConfigInstance.CreateSyncDBProcCommand = string.Concat(dtSyncConfig.Rows[0]["SyncCmd"]);
            }
            else
            {
                ConfigInstanceHelper.ConfigInstance.ErrorMessage = errorMessage;
                return false;
            }

            //在调用前确认(异步执行)
            ////确认升级
            //string msgText = "请确认以下信息无误后完成升级："
            //     + System.Environment.NewLine + "来源产品:" + ConfigInstanceHelper.ConfigInstance.SourceProductName
            //     + System.Environment.NewLine + "目标产品:" + ConfigInstanceHelper.ConfigInstance.TargetProductName
            //     + System.Environment.NewLine + "目标产品所在服务器名称(IP):" + ConfigInstanceHelper.ConfigInstance.TargetServerName
            //     + System.Environment.NewLine + "启用事务一致性:" + (ConfigInstanceHelper.ConfigInstance.EnabledTran ? "是" : "否")
            //     + System.Environment.NewLine + "配置库要同步数据的表:" + ConfigInstanceHelper.ConfigInstance.SyncDataTableNames
            //     ;
            //if (MessageBox.Show(msgText, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            //{
            //    return;
            //}

            if (!string.IsNullOrEmpty(ConfigInstanceHelper.ConfigInstance.CreateSyncDBProcCommand))
            {
                //步骤:
                //1.在目标服务器tempdb创建同步存储过程
                //2.执行同步存储过程
                //3.删除同步存储过程
                string connStr = "Data Source=" + ConfigInstanceHelper.ConfigInstance.TargetServerName + ";User ID=" + ConfigInstanceHelper.ConfigInstance.TargetUserId + ";Password=" + ConfigInstanceHelper.ConfigInstance.TargetUserPassword + ";Initial Catalog=tempdb; persist security info=true";
                SqlConnection conn = new SqlConnection(connStr);
                string Usp_SyncDBName = "Usp_SyncDB" + Guid.NewGuid().ToString().Substring(0, 6);
                try
                {
                    //开启连接
                    conn.Open();


                    //1.在目标服务器tempdb创建同步存储过程
                    //1.1 先删除同名同步存储过程
                    SqlCommand cmdDropProc = new SqlCommand("DROP PROC " + Usp_SyncDBName, conn);
                    try
                    {
                        cmdDropProc.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {

                    }
                    string CreateSyncDBProcCommand = ConfigInstanceHelper.ConfigInstance.CreateSyncDBProcCommand.Replace("Usp_SyncDB", Usp_SyncDBName);
                    //1.2 在目标服务器tempdb创建同步存储过程
                    SqlCommand cmdCreateProc = new SqlCommand(CreateSyncDBProcCommand, conn);
                    cmdCreateProc.ExecuteNonQuery();

                    //2.执行同步存储过程(调用2次)                
                    DataSet dsMasterSyncLog = new DataSet();
                    DataSet dsConfigSyncLog = new DataSet();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();

                    SqlCommand cmd = new SqlCommand(Usp_SyncDBName, conn);
                    cmd.CommandTimeout = 0;
                    cmd.CommandType = CommandType.StoredProcedure;
                    //同步主数据库(只同步结构不同步数据)
                    //参数默认值
                    ConfigInstanceHelper.ConfigInstance.GenerateSyncCommandOnly = false;
                    ConfigInstanceHelper.ConfigInstance.DisabledSyncDataTableNames = "";
                    ConfigInstanceHelper.ConfigInstance.BackupTargetDB = true;
                    cmd.Parameters.Clear();

                    string sourceServerName = ConfigInstanceHelper.ConfigInstance.SourceServerName;
                    string sourceServerNetName = ConfigInstanceHelper.ConfigInstance.SourceServerNetName;
                    string targetServerName = ConfigInstanceHelper.ConfigInstance.TargetServerName;
                    //来源服务器与目标服务器一致时设置来源服务器为空
                    if (sourceServerNetName.ToLower() == targetServerName.ToLower())
                    {
                        sourceServerName = "";
                        sourceServerNetName = "";
                    }
                    cmd.Parameters.Add(new SqlParameter("@SourceServerName", sourceServerName));
                    cmd.Parameters.Add(new SqlParameter("@SourceServerNetName", sourceServerNetName));
                    cmd.Parameters.Add(new SqlParameter("@SourceUserId", ConfigInstanceHelper.ConfigInstance.SourceUserId));
                    cmd.Parameters.Add(new SqlParameter("@SourceUserPassword", ConfigInstanceHelper.ConfigInstance.SourceUserPassword));
                    cmd.Parameters.Add(new SqlParameter("@SourceDB", ConfigInstanceHelper.ConfigInstance.SourceMasterDB));
                    cmd.Parameters.Add(new SqlParameter("@TargetServerName", ""));
                    cmd.Parameters.Add(new SqlParameter("@TargetUserId", ""));
                    cmd.Parameters.Add(new SqlParameter("@TargetUserPassword", ""));
                    cmd.Parameters.Add(new SqlParameter("@TargetDB", ConfigInstanceHelper.ConfigInstance.TargetMasterDB));
                    cmd.Parameters.Add(new SqlParameter("@GenerateSyncCommandOnly", ConfigInstanceHelper.ConfigInstance.GenerateSyncCommandOnly));
                    cmd.Parameters.Add(new SqlParameter("@SyncDataTableNames", ""));
                    cmd.Parameters.Add(new SqlParameter("@DisabledSyncDataTableNames", "*"));
                    cmd.Parameters.Add(new SqlParameter("@BackupTargetDB", ConfigInstanceHelper.ConfigInstance.BackupTargetDB));
                    cmd.Parameters.Add(new SqlParameter("@BackupPath", ConfigInstanceHelper.ConfigInstance.BackupPath));
                    cmd.Parameters.Add(new SqlParameter("@EnabledTran", ConfigInstanceHelper.ConfigInstance.EnabledTran));
                    cmd.Parameters.Add(new SqlParameter("@DeleteExpiredColumn", ConfigInstanceHelper.ConfigInstance.DeleteExpiredColumn));
                    cmd.Parameters.Add(new SqlParameter("@EnabledSyncLog", ConfigInstanceHelper.ConfigInstance.EnabledSyncLog));
                    cmd.Parameters.Add(new SqlParameter("@SyncLogServerSourceType", ConfigInstanceHelper.ConfigInstance.SyncLogServerSourceType));
                    cmd.Parameters.Add(new SqlParameter("@SyncLogDBName", ConfigInstanceHelper.ConfigInstance.SyncLogDBName));
                    cmd.Parameters.Add(new SqlParameter("@OperateUserID", ConfigInstanceHelper.ConfigInstance.OperateUserID));
                    cmd.Parameters.Add(new SqlParameter("@OperateUserName", ConfigInstanceHelper.ConfigInstance.OperateUserName));
                    cmd.Parameters.Add(new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, -1));
                    cmd.Parameters["@ErrorMessage"].Direction = ParameterDirection.Output;

                    sqlDA.SelectCommand = cmd;
                    sqlDA.Fill(dsMasterSyncLog);
                    if (cmd.Parameters["@ErrorMessage"].Value != null)
                    {
                        masterErrorMessage = cmd.Parameters["@ErrorMessage"].Value.ToString();
                        errorMessage = errorMessage + masterErrorMessage;
                    }
                    //记录执行结果
                    ConfigInstanceHelper.ConfigInstance.MasterErrorMessage = masterErrorMessage;
                    ConfigInstanceHelper.ConfigInstance.MasterSyncLogDS = dsMasterSyncLog;

                    //同步配置数据库
                    if (ConfigInstanceHelper.ConfigInstance.SourceMasterDB.ToLower() != ConfigInstanceHelper.ConfigInstance.SourceConfigDB.ToLower() ||
                        ConfigInstanceHelper.ConfigInstance.TargetMasterDB.ToLower() != ConfigInstanceHelper.ConfigInstance.TargetConfigDB.ToLower())
                    {
                        cmd.Parameters["@SourceDB"].Value = ConfigInstanceHelper.ConfigInstance.SourceConfigDB;
                        cmd.Parameters["@TargetDB"].Value = ConfigInstanceHelper.ConfigInstance.TargetConfigDB;
                        cmd.Parameters["@SyncDataTableNames"].Value = ConfigInstanceHelper.ConfigInstance.SyncDataTableNames;
                        cmd.Parameters["@DisabledSyncDataTableNames"].Value = "";
                        sqlDA.SelectCommand = cmd;
                        sqlDA.Fill(dsConfigSyncLog);
                        if (cmd.Parameters["@ErrorMessage"].Value != null)
                        {
                            configErrorMessage = cmd.Parameters["@ErrorMessage"].Value.ToString();
                            errorMessage = errorMessage + configErrorMessage;
                        }
                        //记录执行结果
                        ConfigInstanceHelper.ConfigInstance.ConfigErrorMessage = configErrorMessage;
                        ConfigInstanceHelper.ConfigInstance.ConfigSyncLogDS = dsConfigSyncLog;
                    }

                    //3.删除同步存储过程
                    try
                    {
                        cmdDropProc.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {

                    }

                    //关闭连接
                    conn.Close();
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        syncSuccess = false;
                        ConfigInstanceHelper.ConfigInstance.ErrorMessage = errorMessage;
                        ////写入错误日志
                        //string logFileFullName = AddLogTxt(errorMessage);
                        ////MessageBox.Show("同步时发生错误。" + errorMessage);
                        ////打开错误日志
                        //string exefile = "notepad.exe";
                        //Process process = new Process();   // params 为 string 类型的参数，多个参数以空格分隔，如果某个参数为空，可以传入””
                        //ProcessStartInfo startInfo = new ProcessStartInfo(exefile, logFileFullName);
                        //process.StartInfo = startInfo;
                        //process.Start();
                    }
                    else
                    {
                        //MessageBox.Show("同步成功.");
                        this.lblStatus.Visible = false;
                        syncSuccess = true;
                        ConfigInstanceHelper.ConfigInstance.ErrorMessage = "";


                        string d_connStr = "Data Source=" + ConfigInstanceHelper.ConfigInstance.SourceServerName + ";User ID=" + ConfigInstanceHelper.ConfigInstance.SourceUserId + ";Password=" + ConfigInstanceHelper.ConfigInstance.SourceUserPassword + ";Initial Catalog=QDDevPlat_V4; persist security info=true";
                        SqlConnection d_conn = new SqlConnection(d_connStr);
                        d_conn.Open();

                        //每组同步只保留1条同步记录
                        //主数据库
                        string sql = string.Format(@"delete from Sys_SyncLog where SourceDB='[{0}]' and TargetDB='[{1}]' 
and id<>(select max(ID) from Sys_SyncLog where SourceDB='[{0}]' and TargetDB='[{1}]')
delete from Sys_SyncLogDetail where SyncLogRowIdentifier not in (select RowIdentifier from Sys_SyncLog)", ConfigInstanceHelper.ConfigInstance.SourceMasterDB, ConfigInstanceHelper.ConfigInstance.TargetMasterDB);
                        SqlCommand d_cmd = new SqlCommand(sql, d_conn);
                        d_cmd.ExecuteNonQuery();

                        //配置数据库
                        string sql1 = string.Format(@"delete from Sys_SyncLog where SourceDB='[{0}]' and TargetDB='[{1}]' 
and id<>(select max(ID) from Sys_SyncLog where SourceDB='[{0}]' and TargetDB='[{1}]')
delete from Sys_SyncLogDetail where SyncLogRowIdentifier not in (select RowIdentifier from Sys_SyncLog)", ConfigInstanceHelper.ConfigInstance.SourceConfigDB, ConfigInstanceHelper.ConfigInstance.TargetConfigDB);
                        SqlCommand d_cmd1 = new SqlCommand(sql1, d_conn);
                        d_cmd1.ExecuteNonQuery();
                        d_conn.Close();
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;
                    ConfigInstanceHelper.ConfigInstance.ErrorMessage = errorMessage;
                    //3.删除同步存储过程
                    try
                    {
                        SqlCommand cmdDropProc = new SqlCommand("DROP PROC " + Usp_SyncDBName, conn);
                        cmdDropProc.ExecuteNonQuery();
                    }
                    catch (Exception ex2)
                    {

                    }
                    //throw ex;
                    syncSuccess = false;
                }
                finally
                {
                    conn.Close();
                }
            }
            else
            {
                errorMessage = "同步语句为空";
                ConfigInstanceHelper.ConfigInstance.ErrorMessage = errorMessage;
                return false;
            }
            return syncSuccess;
        }

        /// <summary>
        /// 更新运行时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProcessTimer_Tick(object sender, EventArgs e)
        {
            this.lblStatus.Text = "已运行" + Convert.ToInt32(new TimeSpan(DateTime.Now.Ticks).Subtract(new TimeSpan(StartProcessDate.Ticks)).TotalSeconds).ToString() + "秒";
        }
        private void cbxTableType_TextChanged(object sender, EventArgs e)
        {
            //根据所选表类型自动选中表名
            string selectedText = this.cbxTableType.Text;
            bool rowSelected = false;
            if (string.IsNullOrEmpty(selectedText))
            {
                int rowsCount = this.gridTable.Rows.Count;
                for (int i = 0; i < rowsCount; i++)
                {
                    //this.gridTable.Rows[i].Selected = rowSelected;
                    gridTable.Rows[i].Cells[0].Value = false;
                }
            }
            else
            {
                string[] tableTypeNameList = selectedText.Split(new char[] { ',' }).Select(t => t.Trim()).ToArray();
                int rowsCount = this.gridTable.Rows.Count;
                for (int i = 0; i < rowsCount; i++)
                {
                    rowSelected = tableTypeNameList.Contains(this.gridTable.Rows[i].GetCellValueToString("TableTypeName"));
                    //this.gridTable.Rows[i].Selected = rowSelected;
                    gridTable.Rows[i].Cells[0].Value = rowSelected;
                }
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="txt"></param>
        private string AddLogTxt(string txt)
        {
            string logFileFullName = "";
            try
            {
                StreamWriter writer;
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory + "Error\\";
                string requestText = System.Environment.NewLine + System.Environment.NewLine + DateTime.Now.ToString() + System.Environment.NewLine + txt;

                CreateDirectory(baseDirectory);
                //string str2 = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                string str2 = GetTempFileName(baseDirectory, "SyncError", ".txt", 0);
                logFileFullName = baseDirectory + str2;
                if (File.Exists(baseDirectory + str2))
                {
                    File.AppendAllText(baseDirectory + str2, requestText, Encoding.Unicode);
                }
                else
                {
                    File.WriteAllText(baseDirectory + str2, requestText, Encoding.Unicode);
                }
            }
            catch (Exception except)
            {
            }

            return logFileFullName;
        }
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private DirectoryInfo CreateDirectory(string path)
        {
            DirectoryInfo diReturn = null;
            try
            {
                diReturn = Directory.CreateDirectory(path);
            }
            catch (System.IO.DirectoryNotFoundException except)
            {
                string[] pathList = path.Split('\\');
                for (int i = 0; i < pathList.Length; i++)
                {
                    string tempPath = string.Join("\\", pathList, 0, i + 1);
                    if (Directory.Exists(tempPath))
                    {
                        continue;
                    }
                    else
                    {
                        DirectoryInfo diReturnTemp = Directory.CreateDirectory(tempPath);
                        if (i == pathList.Length - 1)
                        {
                            diReturn = diReturnTemp;
                        }
                    }
                }
            }
            return diReturn;
        }
        /// <summary>
        /// 取不重复的临时文件名称
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="filePrefix"></param>
        /// <param name="fileExt"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        private string GetTempFileName(string filePath, string filePrefix, string fileExt, int maxLength)
        {
            if (fileExt.StartsWith("."))
            {
                fileExt = fileExt.Substring(1, fileExt.Length - 1);
            }
            if (maxLength > 0 && filePrefix.Length + fileExt.Length + 1 > maxLength)
            {
                return "";
            }
            //文件夹不存在时自动创建
            if (!System.IO.Directory.Exists(filePath))
            {
                CreateDirectory(filePath);
            }
            string fileName = "";
            try
            {
                string currentTimeString = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                //string currentTimeString = Guid.NewGuid().ToString();
                string tempFileName = filePrefix + currentTimeString;
                if (maxLength > 0 && tempFileName.Length + fileExt.Length + 1 > maxLength)
                {
                    tempFileName = filePrefix + currentTimeString.Substring(0, maxLength - filePrefix.Length - fileExt.Length - 1);
                }
                string tempFileFullName = filePath + "\\" + tempFileName + "." + fileExt;
                int tryCount = 0;
                while (System.IO.File.Exists(tempFileFullName))
                {
                    currentTimeString = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    if (tryCount > 3 && tryCount <= 10)
                    {
                        currentTimeString = Guid.NewGuid().ToString();
                    }
                    tempFileName = filePrefix + currentTimeString;
                    if (maxLength > 0 && tempFileName.Length + fileExt.Length + 1 > maxLength)
                    {
                        tempFileName = filePrefix + currentTimeString.Substring(0, maxLength - filePrefix.Length - fileExt.Length - 1);
                    }
                    tempFileFullName = filePath + "\\" + tempFileName + "." + fileExt;

                    tryCount++;
                    if (tryCount > 65536)
                    {
                        return "";
                    }
                }
                fileName = tempFileName + "." + fileExt;
            }
            catch (Exception except)
            {
                //AddLogTxt("FileHelper.Except:" + except.Source + Environment.NewLine + except.Message + Environment.NewLine + except.StackTrace);
            }

            return fileName;
        }

        private void gridTable_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0)
            {
                this.gridTable.CurrentCell = this.gridTable.Rows[e.RowIndex].Cells[e.ColumnIndex];
                this.gridTable.CurrentCell.ReadOnly = false;
                this.gridTable.BeginEdit(true);
            }
        }

        private void cbxTableType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //显示行号
        private void gridTable_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, gridTable.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), gridTable.RowHeadersDefaultCellStyle.Font, rectangle, gridTable.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            searchData(-1, true);
        }

        private void btnSearchNext_Click(object sender, EventArgs e)
        {
            int rowIndex = -1;
            DataGridViewCell gridViewCell = this.gridTable.CurrentCell;
            if (gridViewCell != null)
            {
                rowIndex = gridViewCell.RowIndex;
            }
            searchData(rowIndex, true);
        }

        private void searchData(int beginRowIndex, bool searchDownward)
        {
            this.gridTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.gridTable.MultiSelect = true;
            this.gridTable.ClearSelection();

            string serachColumnName = "SysTable";
            string searchColumnValue = this.txtSearchColumnValue.Text;
            int rowsCount = this.gridTable.Rows.Count;
            int firstSelectedRowIndex = -1;
            List<int> selectedRowIndexList = new List<int>();
            int rowIndex = -1;
            string operatorType = "like";

            if (!string.IsNullOrEmpty(serachColumnName) && !string.IsNullOrEmpty(searchColumnValue))
            {
                if (searchColumnValue.StartsWith("="))
                {
                    operatorType = "=";
                    searchColumnValue = searchColumnValue.Substring(1);
                }
                else if (searchColumnValue.StartsWith("%") && searchColumnValue.EndsWith("%"))
                {
                    operatorType = "like";
                    searchColumnValue = searchColumnValue.Substring(1, searchColumnValue.Length - 2);
                }
                else if (searchColumnValue.StartsWith("%") && !searchColumnValue.EndsWith("%"))
                {
                    operatorType = "rightlike";
                    searchColumnValue = searchColumnValue.Substring(1);
                }
                else if (!searchColumnValue.StartsWith("%") && searchColumnValue.EndsWith("%"))
                {
                    operatorType = "leftlike";
                    searchColumnValue = searchColumnValue.Substring(0, searchColumnValue.Length - 1);
                }
                else
                {
                    operatorType = "like";
                }

                if (!string.IsNullOrEmpty(searchColumnValue))
                {
                    for (int i = 0; i < rowsCount; i++)
                    {
                        string columnValue = this.gridTable.Rows[i].GetCellValueToString(serachColumnName);

                        bool matchTag = false;

                        if (!string.IsNullOrEmpty(columnValue))
                        {
                            if ((operatorType == "=" && columnValue.ToLower() == searchColumnValue.ToLower())
                                || (operatorType == "like" && columnValue.ToLower().Contains(searchColumnValue.ToLower()))
                                || (operatorType == "rightlike" && columnValue.ToLower().EndsWith(searchColumnValue.ToLower()))
                                || (operatorType == "leftlike" && columnValue.ToLower().StartsWith(searchColumnValue.ToLower()))
                                )
                            {
                                this.gridTable.Rows[i].Selected = true;
                                selectedRowIndexList.Add(i);
                                if (searchDownward && i > beginRowIndex && firstSelectedRowIndex == -1)
                                {
                                    firstSelectedRowIndex = i;
                                }
                                else if (!searchDownward && i < beginRowIndex && i > firstSelectedRowIndex)
                                {
                                    firstSelectedRowIndex = i;
                                }
                            }
                        }
                    }
                    if (firstSelectedRowIndex != -1)
                    {
                        this.gridTable.FirstDisplayedScrollingRowIndex = firstSelectedRowIndex;
                        this.gridTable.CurrentCell = this.gridTable.Rows[firstSelectedRowIndex].Cells[0];//设定当前行
                        //重新选中行（this.gridTable.CurrentCell会取消选择）
                        for (int i = 0; i < selectedRowIndexList.Count; i++)
                        {
                            rowIndex = selectedRowIndexList[i];
                            this.gridTable.Rows[rowIndex].Selected = true;
                        }
                    }
                }
            }
        }

        private void btnSearchPrev_Click(object sender, EventArgs e)
        {
            int rowIndex = -1;
            DataGridViewCell gridViewCell = this.gridTable.CurrentCell;
            if (gridViewCell != null)
            {
                rowIndex = gridViewCell.RowIndex;
            }
            searchData(rowIndex, false);
        }
    }
}
